package com.bkhech.netty.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.dialect.Props;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * CuratorConfig
 *  Curator 客户端
 * @author guowm
 * @date 2024-11-20
 */
@Slf4j
public class CuratorConfig {

    private static volatile CuratorFramework client;

    private static CuratorFramework init() {
        final Props properties = PropertiesUtil.getInstance();
         // 每次重试的间隔时间
        int sleepMsBetweenRetry = properties.getInt("zookeeper.sleepMsBetweenRetry");
        // 最大重试次数
        int maxRetries = properties.getInt("zookeeper.maxRetries");
        // 连接超时时间
        int connTimeoutMs = properties.getInt("zookeeper.connTimeoutMs");
         // 会话连接超时时间
        int sessionTimeoutMs = properties.getInt("zookeeper.sessionTimeoutMs");
        // ip:port,ip2:port2
        String addr = properties.getProperty("zookeeper.host");
        String port = properties.getProperty("zookeeper.port");
        // 命名空间（root 根节点名称）
        String namespace = properties.getProperty("zookeeper.namespace");
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(sleepMsBetweenRetry, maxRetries);

        try {
            client = CuratorFrameworkFactory.builder()
                    .retryPolicy(retryPolicy)
                    .connectionTimeoutMs(connTimeoutMs)
                    .sessionTimeoutMs(sessionTimeoutMs)
                    .namespace(namespace)
                    .connectString(addr + StrUtil.COLON + port)
                    .build();
        } catch (Exception e) {
            log.error("获取本机IP失败：{},{}", e, e.getMessage());
            throw new RuntimeException(e);
        }
        client.start();
        return client;

    }

    public static CuratorFramework getClient() {
        if (client == null) {
            synchronized (CuratorConfig.class) {
                if (client == null) {
                    client = init();
                }
            }
        }
        return client;
    }

}
